package com.situ.mall.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.situ.mall.common.entity.*;
import com.situ.mall.common.mapper.*;
import com.situ.mall.common.service.IOrderInfoService;
import com.situ.mall.common.util.RequestUtil;
import com.situ.mall.common.vo.TableVO;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kkkkkk
 * @since 2023-09-18
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private MemberAddressMapper memberAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderInfo saveOrder(String ids, Integer addressId) {
        Member m = (Member) RequestUtil.getCurrent();
        //创建一个OrderInfo对象　　　保存到数据库
        OrderInfo oi = new OrderInfo();
        //UUID  GUID
        // 雪花算法（推荐）
        // 流水号
        oi.setCode("O-" + System.currentTimeMillis());
        oi.setCreatetime(LocalDateTime.now());
        oi.setStatus("待支付");
        oi.setMemberId(m.getId());
        oi.setPayType("alipay");
        BigDecimal sum = new BigDecimal("0");
        for (String cid : ids.split(",")) {
            Cart c = cartMapper.selectById(Integer.parseInt(cid));
            Product p = productMapper.selectById(c.getProductId());
            sum = sum.add(p.getPrice().multiply(new BigDecimal(c.getAmount())));
        }
        oi.setTotalPrice(sum);
        baseMapper.insert(oi);

        //创建多个OrderDetail　　保存进数据库
        for (String cid : ids.split(",")) {
            Cart c = cartMapper.selectById(Integer.parseInt(cid));
            Product p = productMapper.selectById(c.getProductId());
            OrderDetail od = new OrderDetail();
            od.setOrderId(oi.getId());
            od.setAmount(c.getAmount());
            od.setPrice(p.getPrice());
            od.setProductId(c.getProductId());
            orderDetailMapper.insert(od);
        }
        //创建OrderAddress对象　　保存进数据库
        MemberAddress ma = memberAddressMapper.selectById(addressId);
        OrderAddress oa = new OrderAddress();
        BeanUtils.copyProperties(ma, oa);//用时注意导包问题
        oa.setOrderId(oi.getId());
        oa.setId(null);
        orderAddressMapper.insert(oa);
        //把购物车中原来的数据删除
        for (String cid : ids.split(",")) {
            cartMapper.deleteById(Integer.parseInt(cid));
        }

        //往MQ中放一个消息：放上订单的ID
        delaySend(new ActiveMQQueue("aaa"), oi.getId(), 15*60 * 1000L);
        return oi;
    }


    private <T extends Serializable> void delaySend(Destination queue, T data, Long time) {
        Connection conn = null;
        Session session = null;
        MessageProducer producer = null;

        ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
        try {
            conn = connectionFactory.createConnection();
            conn.start();
            session = conn.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //创建一个生产者
            producer = session.createProducer(queue);
            producer.setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT.getValue());
            ObjectMessage message = session.createObjectMessage(data);
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
            producer.send(message);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (producer != null) {
                    producer.close();
                }
                if (session != null) {
                    session.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception ignored) {

            }
        }
    }

    @Override
    public TableVO orderList(Integer page, Integer limit, String status, String keyword) {
        Member m = (Member) RequestUtil.getCurrent();
        PageHelper.startPage(page, limit);
        return TableVO.data(baseMapper.orderList(status, keyword, m.getId()));
    }

    @Override
    public void paySuccess(String code) {
        baseMapper.paySuccess(code);
    }
}
